<?php

namespace App\Models\Sku;

//use Illuminate\Database\Eloquent\Model;
use App\Models\ExModel;
use Laracasts\Presenter\PresentableTrait;

class Product extends ExModel
{
    use PresentableTrait;

	protected $table = 'sku_products';

    protected $fillable = ['name','title','sub_title','category_id','shop_id','detail','service','effect','date_n','date_begin','date_end',
        'score','status','is_hot','is_new','is_recommend','virtual_sales','sort','cover_pic','share_pic'];

	protected $guarded = array();

    protected $with=['orderItems'];

    protected $presenter = 'App\Http\Presenters\Sku\ProductPresenter';

	public  function  setDateBeginAttribute($value)
    {
        $this->attributes['date_begin'] = strtotime($value);
    }

    public  function  setDateEndAttribute($value)
    {
        $this->attributes['date_end'] = strtotime($value);
    }

    public function  getDateBeginAttribute(){
        return date('Y-m-d H:i:s',$this->attributes['date_begin']);
    }

    public  function  getDateEndAttribute(){
        return date('Y-m-d H:i:s',$this->attributes['date_end']);
    }


	public function shop()
	{
		return $this->belongsTo('\App\Models\Biz\Shop');
	}

	public function attrs()
	{
		return $this->hasMany('\App\Models\Sku\Attr');
	}

	public function specs()
	{
		return $this->hasMany('\App\Models\Sku\Spec');
	}

	public function items()
	{
		return $this->hasMany('\App\Models\Sku\Item');
	}

    /**
     * 从订单详情中获取销量
     *
     * @return void
     */
    public function itemsCount()
    {
        return $this->orderItems->sum('number');
    }

    public function orderItems()
	{
		return $this->hasMany('\App\Models\Odr\Item');
	}


	public function category()
	{
		return $this->belongsTo('\App\Models\Mgt\Category');
	}

    /**
     * 上传图片并更新图片字段
     *
     * @param [type] $request
     * @return void
     */
	public function setImages($request)
	{        
		if( $request->hasFile('cover_pic') && $request->hasFile('share_pic') ){

            $dir = public_path().UPLOAD_PATH.date('Ymd').'/';

            $files = $request->files;

            foreach ($files as $file) {

                $entension = $file->getClientOriginalExtension();

                $filename = $this->id.'_'.mt_rand(100000,999999).'.'.$entension;

                $file->move($dir,$filename);

                $filepath[] = UPLOAD_PATH.date('Ymd').'/'.$filename;
            }

            $this->update([
                'cover_pic' => $filepath[0],
                'share_pic' => $filepath[1],
            ]);
        }
	}


    /**
     * 图片有变化便更新图片和数据库
     *
     * @param [type] $request
     * @return void
     */
	public function updateImages($request)
	{
        $dir = public_path().UPLOAD_PATH.date('Ymd').'/';
		
        if( $request->hasFile('cover_pic') ){            
            $file = $request->cover_pic;
            if(filesize($file) !== filesize(public_path().$this->cover_pic)){
                $entension = $file->getClientOriginalExtension();
                $filename = $this->id.'_'.mt_rand(100000,999999).'.'.$entension;
                $file->move($dir,$filename);
                $filepath = UPLOAD_PATH.date('Ymd').'/'.$filename;
            }
            $this->update(['cover_pic' => $filepath]);
        }

        if( $request->hasFile('share_pic') ){            
            $file = $request->share_pic;
            if(filesize($file) !== filesize(public_path().$this->share_pic)){
                $entension = $file->getClientOriginalExtension();
                $filename = $this->id.'_'.mt_rand(100000,999999).'.'.$entension;
                $file->move($dir,$filename);
                $filepath = UPLOAD_PATH.date('Ymd').'/'.$filename;
            }
            $this->update(['share_pic' => $filepath]);
        }
	}


    /**
     * 设置SKU信息，如无SKU则插入默认SKU
     *
     * @param [type] $request
     * @return void
     */
	public function setItems($request)
    {
        if( isset($request->sku)) {

            foreach($request->sku as $sku){

                $attrList = array();

                foreach($sku[SKU_LIST] as $attr){
                    //属性
                    $skuAttr = \App\Models\Sku\Attr::pid($this->id)->where('name',$attr[SKU_ATTR])->first();
                    if(!$skuAttr)
                        $skuAttr = \App\Models\Sku\Attr::create(['product_id'=>$this->id,'name'=>$attr[SKU_ATTR]]);

                    //规格
                    $skuSpec = \App\Models\Sku\Spec::pid($this->id)->where('attr_id',$skuAttr->id)->where('name',$attr[SKU_SPEC])->first();
                    if(!$skuSpec)
                        $skuSpec = \App\Models\Sku\Spec::create(['product_id'=>$this->id,'attr_id'=>$skuAttr->id,'name'=>$attr[SKU_SPEC]]);

                    $attrList[] = $skuAttr->id.':'.$skuSpec->id;

                }
                //写SKU item
                \App\Models\Sku\Item::create([
                    'product_id' => $this->id,
                    'sku' => json_encode($attrList),
                    'price' => $sku['price'],
                    'origin' => $sku['origin'],
                    'settlement' => $sku['settlement'],
                    'stock' => $sku['stock'],
                ]);

                $this->update(['sku_flag' => STATUS_NORMAL]);
            }

            event(new \App\Events\AddSkuEvent($this));

        }
        //无SKU
        else{
            $skuAttr = \App\Models\Sku\Attr::create(['product_id'=>$this->id,'name'=>SKU_NAME]);
            $skuSpec = \App\Models\Sku\Spec::create(['product_id'=>$this->id,'attr_id'=>$skuAttr->id,'name'=>SKU_NAME]);
            $attrList[] = $skuAttr->id.':'.$skuSpec->id;
            \App\Models\Sku\Item::create([
                'product_id' => $this->id,
                'sku' => json_encode($attrList),
                'price' => $request->price,
                'origin' => $request->origin,
                'settlement' => $request->settlement,
                'stock' => $request->stock,
            ]);
        }
    }


    public function updateItems($request)
    {
        if( isset($request->sku)) {

            foreach($request->sku as $sku){

                \App\Models\Sku\Item::where('id',$sku['id'])
                ->update([
                    'price' => $sku['price'],
                    'origin' => $sku['origin'],
                    'settlement' => $sku['settlement'],
                    'stock' => $sku['stock'],
                ]);
            }

        }
        //无SKU
        else{
            $item = $this->items->first();

            $item->update([
                'price' => $request->price,
                'origin' => $request->origin,
                'settlement' => $request->settlement,
                'stock' => $request->stock,
            ]);
        }
    }


	public function sale($str)
	{
		$result = $this->items->first();

		switch ($str) {
			case 'price':
				return $result->price;
				break;
			case 'origin':
				return $result->origin;
				break;
			case 'settlement':
				return $result->settlement;
				break;
			default:
				# code...
				break;
		}
		
	}

}